const Koa = require("koa");
const path = require("path");
const { ServerConfig } = require("./libs/config");
const handlerError = require("./middlewares/handlerError");
const koaAuth = require("./middlewares/auth");
const { notFound } = require("./middlewares/notFound");
const session = require("koa-session");
const compose = require("koa-compose");
const helmet = require("koa-helmet");
const KoaStatic = require("koa-static");
const koaBody = require("koa-body");
const useRoute = require("./libs/router");

const app = new Koa();

app.keys = ["login_checkCode_z"]; //设置前面的cookie密钥数组
app.proxy = true;
const SessionConfig = {
  key: "koa:checkCodez",
  maxAge: 86400000, //过期时间
  overwrite: true, //是否可以overwrite,重写
  httpOnly: true, //
  signed: true,
  rolling: false,
  renew: false,
};

app.use(
  compose([
    handlerError,
    session(SessionConfig, app),
    helmet(),
    KoaStatic(path.join(__dirname, "../static")),
    koaBody({
      multipart: true,
      uploadDir: path.join(__dirname, "../static/upload"),
      formidable: {
        maxFieldsSize: 1024 * 1024 * 1024 * 3,
      },
    }),
    koaAuth,
  ])
);

// 处理跨域
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set(
    "Access-Control-Allow-Headers",
    "Content-Type,b-json-web-token, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild"
  );
  ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
  if (ctx.method == "OPTIONS") {
    ctx.body = 200;
  } else {
    await next();
  }
});

useRoute(app);

app.use(compose([notFound]));

app.on("error", (err) => {
  console.log("server error", err);
  console.error("server error", err);
});

app.listen(ServerConfig.port || 8081);
